import { query } from '$lib/config/db';

const permissionsModule = {
  getById: async (id) => {
    const sql = 'SELECT * FROM permissions WHERE id = $1';
    const params = [id];
    const rows = await query(sql, params);
    return rows[0];
  },
  getByRoleId: async (roleId) => {
    const sql = `SELECT json_build_object( 'role', json_build_object( 'id', r.id, 'code', r.code, 'name', r.name, 'description', r.description ), 'permissions', json_agg( json_build_object( 'id', p.id, 'name', p.name, 'handle', p.handle, 'icon', p.icon, 'sort', p.sort, 'parent_id', p.parent_id, 'created_at', p.created_at, 'updated_at', p.updated_at ) ORDER BY p.sort ASC ) ) AS role_permissions FROM roles r LEFT JOIN role_permission rp ON rp.role_id = r.id LEFT JOIN permissions p ON p.id = rp.permission_id WHERE r.id = $1 GROUP BY r.id`;
    const params = [roleId];
    const rows = await query(sql, params);
    return rows[0].role_permissions;
  },
  getAll: async () => {
    const sql = 'SELECT * FROM permissions';
    return await query(sql);
  }
}

export default permissionsModule;